import { Link, useLocation } from '@tanstack/react-router'
import { cn } from '@/lib/utils'
import { 
  LayoutDashboard,
  Users,
  Stamp,
  MapPin,
  ShoppingCart,
  Settings,
  ChevronDown,
  ChevronRight
} from 'lucide-react'
import { useState, useEffect } from 'react'

interface NavItem {
  title: string
  href?: string
  icon: React.ElementType
  children?: NavItem[]
}

const navigation: NavItem[] = [
  {
    title: '仪表板',
    href: '/dashboard',
    icon: LayoutDashboard,
  },
  {
    title: '用户管理',
    href: '/users',
    icon: Users,
  },
  {
    title: '在线刻章',
    icon: Stamp,
    children: [
      {
        title: '订单管理',
        href: '/seals/orders',
        icon: ShoppingCart,
      },
      {
        title: '区域印章配置',
        href: '/seals/regions',
        icon: MapPin,
      },
      {
        title: '刻章配置',
        href: '/seals',
        icon: Stamp,
      },
    ],
  },
  {
    title: '通用配置',
    href: '/settings',
    icon: Settings,
  },
]

interface SidebarProps {
  className?: string
}

export function Sidebar({ className }: SidebarProps) {
  return (
    <div className={cn('w-64 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 h-full', className)}>
      {/* 导航菜单 */}
      <nav className="px-4 py-6 space-y-1 overflow-y-auto h-full">
        {navigation.map((item) => (
          <NavItem key={item.title} item={item} />
        ))}
      </nav>
    </div>
  )
}

interface NavItemProps {
  item: NavItem
  level?: number
}

function NavItem({ item, level = 0 }: NavItemProps) {
  const location = useLocation()
  
  const isActive = item.href ? location.pathname === item.href : false
  const hasChildren = item.children && item.children.length > 0

  // 检查子项是否有激活状态
  const hasActiveChild = hasChildren && 
    item.children!.some(child => location.pathname === child.href)

  // 如果有子项处于激活状态，则自动展开；否则根据点击状态决定
  const [manualExpanded, setManualExpanded] = useState(false)
  const isExpanded = hasActiveChild || manualExpanded

  // 当路由变化且当前模块没有激活子项时，重置手动展开状态
  useEffect(() => {
    if (!hasActiveChild) {
      setManualExpanded(false)
    }
  }, [location.pathname, hasActiveChild])

  const handleClick = () => {
    if (hasChildren) {
      setManualExpanded(!manualExpanded)
    }
  }

  if (hasChildren) {
    return (
      <div>
        <button
          onClick={handleClick}
          className={cn(
            'w-full flex items-center justify-between px-3 py-2 text-sm font-medium rounded-md transition-colors',
            'hover:bg-gray-100 dark:hover:bg-gray-700',
            hasActiveChild
              ? 'bg-blue-50 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300'
              : 'text-gray-700 dark:text-gray-300'
          )}
          style={{ paddingLeft: `${12 + level * 16}px` }}
        >
          <div className="flex items-center">
            <item.icon className="mr-3 h-5 w-5" />
            {item.title}
          </div>
          {isExpanded ? (
            <ChevronDown className="h-4 w-4" />
          ) : (
            <ChevronRight className="h-4 w-4" />
          )}
        </button>
        
        {isExpanded && (
          <div className="mt-1 space-y-1">
            {item.children!.map((child) => (
              <NavItem key={child.title} item={child} level={level + 1} />
            ))}
          </div>
        )}
      </div>
    )
  }

  return (
    <Link
      to={item.href!}
      className={cn(
        'flex items-center px-3 py-2 text-sm font-medium rounded-md transition-colors',
        'hover:bg-gray-100 dark:hover:bg-gray-700',
        isActive
          ? 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300'
          : 'text-gray-700 dark:text-gray-300'
      )}
      style={{ paddingLeft: `${12 + level * 16}px` }}
    >
      <item.icon className="mr-3 h-5 w-5" />
      {item.title}
    </Link>
  )
}
